program client1;

{ this program exists only for testing purposes until all the
  units are in their final form and somehow usable }

{$mode objfpc}{$H+}

uses
  cmem,{$IFDEF UNIX}cthreads,{$ENDIF}
  Classes, sysutils, bitcoin_p2p, logging, bitcoin_peerfinder;

const
  MAX_PEERS = 5;


var
  I          : Integer;
  Peers      : array[1..MAX_PEERS] of TPeer;
  PeerAddr   : TStrAddrAndPort;

{$R *.res}

begin
  {$warning need to find a simple cross platform way to catch SIGINT (Ctrl-C)}
  {$ifdef UNIX}
  HookSignal(RTL_SIGINT);
  {$endif}
  try
    for I := 1 to Length(Peers) do begin
      PeerAddr := GetAnotherPeerAddress4;
      Peers[I] := TPeer.Create(PeerAddr.StrAddr, PeerAddr.Port);
      Peers[I].Start;
    end;
    repeat
      for I := 1 to Length(Peers) do begin
        if Peers[I].CanFree then begin
          log('peer %s failed, trying another one', [Peers[i].PeerAddress]);
          RemoveAddress4FromDb(Peers[I].PeerAddress);
          Peers[I].Free;
          PeerAddr := GetAnotherPeerAddress4;
          Peers[I] := TPeer.Create(PeerAddr.StrAddr, PeerAddr.Port);
          Peers[I].Start;
        end;
      end;
      Sleep(1000);
    until False;
  except
    on E: Exception do begin
      // this is most likely the SIGINT (user pressed Ctrl-C)
      // Since this is only a test progam while developing the bitcoin_p2p
      // unit, I don't make any attempts to orderly shutdown the peers (yet),
      // all I need for now is a way to make it close the dbf tables and
      // therefore it must reach the last "end." to call all finalization
      // sections.
      log(E.Message);
      log('excuting all finalization sections now while terminating.');
    end;
  end;
end.

